<?php

/**
 * PagerTest
 *
 * @author vbolshov
 */

use km\util\Pager;
use km\db\Select;

use \TestDb;

use \PHPUnit_Framework_TestCase;
use \PagerTest;

require_once dirname(__FILE__) . '/../../lib/km/db/Select.php';
require_once dirname(__FILE__) . '/../../lib/km/util/Pager.php';
require_once dirname(__FILE__) . '/../Db.php';

class PagerTest extends PHPUnit_Framework_TestCase {
	function testPlainPager()
	{
		$p = new Pager(2, 1, 1);
		$p->setRanger('plain');
		$this->assertEquals(array(1, 2), $p->getPages());
	}
	function testWindowingPager()
	{
		$p = new Pager(5, 3, 1);
		$p->setRanger('windowing', array('size' => 3));
		$this->assertEquals(array(2, 3, 4), $p->getPages());
		
		$p->setRanger('windowing', array('size' => 4));
		$this->assertEquals(array(2, 3, 4, 5), $p->getPages());
		
		$p = new Pager(10, 1, 1);
		$p->setRanger('windowing', array('size' => 3));
		$this->assertEquals(array(1, 2, 3), $p->getPages());
		
		$p = new Pager(10, 10, 1);
		$p->setRanger('windowing', array('size' => 3));
		$this->assertEquals(array(8, 9, 10), $p->getPages());
	}
	function testUrlGenerating()
	{
		$p = new Pager(1, 1, 1);
		
		$this->assertEquals('?page=1', $p->url(1));
		
		$p->setUrlFormat('/page/%d/');
		$this->assertEquals('/page/1/', $p->url(1));
	}
	function testIterator()
	{
		$p = new Pager(2, 1, 1);
		$p->setRanger('plain');
		
		$expected = array(
			array('number' => 1, 'url' => '?page=1', 'selected' => true),
			array('number' => 2, 'url' => '?page=2', 'selected' => false)
		);
		
		foreach ($p as $i => $page)
		{
			$this->assertEquals($expected[$i], $page);
		}
	}
	function testLastAndFirst()
	{
		$p = new Pager(1, 1, 1);
		$this->assertTrue($p->isFirst());
		$this->assertTrue($p->isLast());
		
		$p = new Pager(2, 1, 1);
		$this->assertTrue($p->isFirst());
		$this->assertFalse($p->isLast());
		
		$p = new Pager(2, 2, 1);
		$this->assertFalse($p->isFirst());
		$this->assertTrue($p->isLast());
		
		$p = new Pager(3, 2, 1);
		$this->assertFalse($p->isFirst());
		$this->assertFalse($p->isLast());
	}
	function testSelectPagination()
	{
		$pdo = TestDb::connect();
		// create a table and 2 rows in it
		try {
			$pdo->query('DROP TABLE test');
		} catch (PDOException $e) {}
		$pdo->query('CREATE TABLE test (id INT)');
		$pdo->query('INSERT INTO test (id) VALUES (1)');
		$pdo->query('INSERT INTO test (id) VALUES (2)');
		
		Select::setDefaultConnection($pdo);
		
		$s = new Select('test');
		$s->order('id');
		
		$p = new Pager($s, 1, 1);
		$p->setRanger('plain');
		
		$this->assertEquals(array(1, 2), $p->getPages());
		
		$rows = $s->fetchAll();
		
		$this->assertEquals(1, count($rows));
		$this->assertEquals(1, $rows[0]['id']);
	}
}